# 打印数据集的前5行
import pandas as pd
# 确保URL是正确的
url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
df = pd.read_csv(url)
print(df.head())# 使用matplotlib绘制企鹅物种的分布条形图
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
df['Species'].value_counts().plot(kind='bar')
plt.xlabel('Species')
plt.ylabel('Count')
plt.title('Distribution of Penguin Species')
plt.show()# 导入seaborn库
import seaborn as sns
# 使用seaborn绘制箱型图，展示不同物种的FlipperLength、CulmenLength和CulmenDepth的分布
sns.boxplot(data=df, x='Species', y='FlipperLength')
plt.title('Flipper Length Distribution by Species')
plt.show()

sns.boxplot(data=df, x='Species', y='CulmenLength')
plt.title('Culmen Length Distribution by Species')
plt.show()

sns.boxplot(data=df, x='Species', y='CulmenDepth')
plt.title('Culmen Depth Distribution by Species')
plt.show()# 显示缺失值
print(df.isnull().sum())# 删除缺失值
df_clean = df.dropna()# 特征是CulmenLength、CulmenDepth、FlipperLength，标签是Species
X = df_clean[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
y = df_clean['Species']# 将数据集分割为训练集和测试集，测试集占30%
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)# 训练逻辑回归模型
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(multi_class='multinomial', solver='lbfgs', max_iter=200)
model.fit(X_train, y_train)# 评估模型
from sklearn.metrics import accuracy_score
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f'Model Accuracy: {accuracy:.2f}')